package com.macro.mall.utils;


import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpUrlAndFile {

    public static File  getFile(String urlS,String fileName)  {

        try {
            URL url = new URL(urlS);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
            conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
            InputStream inputStream = conn.getInputStream();
            //System.out.println(inputStream);
            //File file = new File(ResourceUtils.getURL("classpath:").getPath());
            //file.createNewFile();
            File newFile = new File("/home", "1.jpg");
            System.out.println(newFile.getPath());
            if (newFile.exists())
                newFile.delete();
            newFile.createNewFile();
            writeToLocal(newFile.getPath(),inputStream);
            conn.disconnect();
            return newFile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void writeToLocal(String destination, InputStream input)
            throws IOException {
        long start = System.currentTimeMillis();
        int index;
        byte[] bytes = new byte[8*1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        BufferedInputStream fis = new BufferedInputStream(input);
        BufferedOutputStream fos = new BufferedOutputStream( new FileOutputStream(destination));
        while ((index = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, index);
            fos.flush();
        }
        input.close();
        downloadFile.close();
        long end = System.currentTimeMillis();   //获取毫秒值
        System.out.println("缓冲流使用字节数组复制时间：" + (end - start) + "毫秒");
    }
//    public static void main(String[] args) throws IOException {
//        //下载的地址
//        String url = "https://satecn.oss-accelerate.aliyuncs.com/mall/images/20200928/63876aa4a45fe16a[1].jpg";
//        getFile(url, "aa.jpg");
//
//    }

}
